//
//  KLImageScrollView.m
//  KunLun
//
//  Created by Mac on 2018/3/21.
//  Copyright © 2018年 stoneobs@icloud.com. All rights reserved.
//

#import "KLImageScrollView.h"
#import "KLUtils.h"
#define buttonWith 100
@interface KLImageScrollView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property(nonatomic, strong) STLabel                     *titlaLable;
@property(nonatomic, strong) UICollectionView                     *collectionView;
@property(nonatomic, strong) STButton                     *addButton;
@property(nonatomic, strong) NSMutableArray                     *imageUrl;
@end
@implementation KLImageScrollView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self configSubView];
    }
    return self;
}
- (BOOL)isSendAll{
    if (self.imageUrl.count == self.dataSouce.count) {
        return YES;
    }
    return NO;
}
- (NSArray *)urlArray{
    return self.imageUrl;
}
- (void)setTitle:(NSString *)title{
    _title = title;
    self.titlaLable.text = title;
}
- (void)setDataSouce:(NSArray<STUrlPhotoModel *> *)dataSouce{
    _dataSouce = dataSouce;
    [self.collectionView reloadData];
    
    self.imageUrl = [NSMutableArray new];
    for (STUrlPhotoModel * model in self.dataSouce) {
        if (model.thumbImageUrl.length && ![self.imageUrl containsObject:model.thumbImageUrl]) {
            [self.imageUrl addObject:model.thumbImageUrl];
        }
    }
}
#pragma mark --subView
- (void)configSubView{
    self.imageUrl = [NSMutableArray new];
    self.titlaLable = [[STLabel alloc] initWithFrame:CGRectMake(0, 0, self.width, 30)
                                                     text:self.title
                                                textColor:FirstTextColor
                                                     font:14
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentLeft];
    [self addSubview:_titlaLable];
    
    UICollectionViewFlowLayout * flow = [UICollectionViewFlowLayout new];
    flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flow.minimumLineSpacing = 5;
    flow.minimumInteritemSpacing = 5;
    __weak typeof(self) weakSelf =  self;
    self.addButton = [[STButton alloc] initWithFrame:CGRectMake(0, self.titlaLable.bottom, 100, 100)
                                               title:@""
                                          titleColor:nil
                                           titleFont:0
                                        cornerRadius:0
                                     backgroundColor:KL_backgroundColor
                                     backgroundImage:nil
                                               image:[UIImage imageNamed:@"sz_xiangce"]];
    self.addButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [self.addButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedAddImageButton:sender];
    }];
    [self addSubview:self.addButton];
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(105, _titlaLable.bottom, self.width - 105, buttonWith) collectionViewLayout:flow];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.collectionView registerClass:[KLImageCollectionViewCell class] forCellWithReuseIdentifier:@"item"];
    [self addSubview:self.collectionView];

    self.height = self.collectionView.bottom;
}
#pragma mark --Action Method
- (void)onSelectedAddImageButton:(UIButton*)sender{
    UITabBarController * tabbarVC = (id)[UIApplication sharedApplication].keyWindow.rootViewController;
    UINavigationController * nav = (id)tabbarVC.childViewControllers[tabbarVC.selectedIndex];
    UIViewController * vc = (id)self.delegate;
    [vc showSTImagePickerHandle:^(NSArray<STPhotoModel *> *array) {

        NSMutableArray *originDataSouce = [self.dataSouce mutableCopy];
        if (!originDataSouce) {
            originDataSouce = [NSMutableArray new];
        }
        for (STPhotoModel * model in array) {
            STUrlPhotoModel * newModel = [STUrlPhotoModel new];
            UIImage * image = model.thumbImage;
            if (model.originImage) {
                image = model.originImage;
            }
            newModel.thumbImage = image;
            [originDataSouce addObject:newModel];
        }
        self.dataSouce =  originDataSouce;

        
    } pickerBlock:^(UIImage *image) {
        NSMutableArray *originDataSouce = [self.dataSouce mutableCopy];
        STUrlPhotoModel * newModel = [STUrlPhotoModel new];
        newModel.thumbImage = image;
        [originDataSouce addObject:newModel];
        self.dataSouce =  originDataSouce;
    }];
}
- (void)sendImageToQiNiu{

    if (self.imageUrl.count == self.dataSouce.count && self.delegate && [self.delegate respondsToSelector:@selector(klimageScrollView:didSendImageUrls:)]) {
        [self.delegate klimageScrollView:self didSendImageUrls:self.imageUrl];
        return;
    }
    for (NSInteger i = 0;i < self.dataSouce.count ; i ++) {
      __block  STUrlPhotoModel * model  = self.dataSouce[i];
        if (!model.thumbImageUrl.length) {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                [KLUtils sendQiNiuWithImage:model.thumbImage handle:^(NSString *imageUrlqn, NSString *errorDes) {
                    if (![self.imageUrl containsObject:imageUrlqn]) {
                        [self.imageUrl addObject:imageUrlqn];
                    }
                    NSLog(@"图片%@",imageUrlqn);
                    model.thumbImageUrl = imageUrlqn;
                    if (self.imageUrl.count == self.dataSouce.count) {
                        //上传完毕
                        if (self.delegate && [self.delegate respondsToSelector:@selector(klimageScrollView:didSendImageUrls:)]) {
                            [self.delegate klimageScrollView:self didSendImageUrls:self.imageUrl];
                        }
                    }
                }];
            });

        }else{
            if (![self.imageUrl containsObject:model.thumbImageUrl]) {
                [self.imageUrl addObject:model.thumbImageUrl];
            }
            if (self.imageUrl.count == self.dataSouce.count) {
                //上传完毕
                if (self.delegate && [self.delegate respondsToSelector:@selector(klimageScrollView:didSendImageUrls:)]) {
                    [self.delegate klimageScrollView:self didSendImageUrls:self.imageUrl];
                }
            }
        }
    }
}
#pragma --mark UICollectionViewDataSource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataSouce.count;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(100, 100);
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    __weak typeof(self) weakSelf =  self;
    KLImageCollectionViewCell * item =[collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
    item.model = self.dataSouce[indexPath.item];
    [item.iconButton setCloseAction:^(UIButton *sender) {
        [weakSelf onSlectedRemoveButtonWithIndexPath:indexPath];
    }];
    return item;
}
- (void)onSlectedRemoveButtonWithIndexPath:(NSIndexPath*)indexPath{
    [self.dataSouce removeObjectAtIndex:indexPath.row];
    self.dataSouce = self.dataSouce;
    [self.collectionView reloadData];
}
#pragma --mark UICollectionViewDelegate
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    [self.collectionView deselectItemAtIndexPath:indexPath animated:NO];
}

@end


@interface KLImageCollectionViewCell()

@end
@implementation KLImageCollectionViewCell
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self configSubView];
    }
    return self;
}
#pragma mark --subView
- (void)configSubView{
    self.iconButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, buttonWith, buttonWith)
                                                     title:nil
                                                titleColor:nil
                                                 titleFont:0
                                              cornerRadius:0
                                           backgroundColor:nil
                                           backgroundImage:nil
                                                     image:nil];
    [self.iconButton setShowCloseButton:YES];
    [self addSubview:self.iconButton];
}
- (void)setModel:(STUrlPhotoModel *)model{
    _model = model;
    if (model.thumbImage) {
        [self.iconButton setImage:model.thumbImage forState:UIControlStateNormal];
    }else{
        [self.iconButton sd_setImageWithURL:[NSURL URLWithString:model.thumbImageUrl] forState:UIControlStateNormal];
    }
}
@end
